const router = require("koa-router")();
const VisitorModel = require("../models/visitor.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");
const formatDateHelper = require('../utils/formatDateHelper.js')


router.get("/visitors", async ctx => {
	let {
		page,
		limit,
		room_id,
		status,
		create
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};

	if (create) {
		query.create = {
			$regex: ctx.query.create
		}; // 不区分大小写的正则表达式
	}

	if (status != undefined && status !== '0') {
		query.status = status;
	}


	if (room_id != undefined && room_id !== '0') {
		query.room_id = room_id;
	}


	var data = await VisitorModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await VisitorModel.find(query).countDocuments();

	ctx.body = {
		code: 200,
		data: data,
		total,
		msg: "ok"
	}

})

router.post("/visitor", async ctx => {

	const {
		house_id,
		room_id,
		name,
		content,
		phone,
		status,
		create,
		modify
	} = ctx.request.body;

	if (!house_id) {
		return ResultHelper.errInfo422(ctx, "请选择单元楼")
	}

	if (!room_id) {
		return ResultHelper.errInfo422(ctx, "请选择户号")
	}

	if (!name) {
		return ResultHelper.errInfo422(ctx, "请填写拜访人姓名")
	}

	if (!content) {
		return ResultHelper.errInfo422(ctx, "请填写拜访事由")
	}

	if (!phone) {
		return ResultHelper.errInfo422(ctx, "请填写联系方式")
	}

	const visitorPost = new VisitorModel({
		house_id,
		room_id,
		name,
		content,
		phone,
		status: 1,
		create,
		modify
	});
	const res = await visitorPost.save();
	ctx.body = {
		code: 200,
		msg: "添加成功"
	}

})

router.post("/pass", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		status
	} = ctx.request.body;
	const res = await VisitorModel.updateOne({
		id: id
	}, {
		$set: {
			id,
			status
		}
	});
	ctx.body = {
		code: 200,
		msg: "ok"
	}

})

router.get("/del/visitor", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id
	} = ctx.request.query;
	let res = await VisitorModel.deleteOne({
		id: id
	});
	ctx.body = {
		code: 200,
		msg: '删除成功'
	}
})


module.exports = router;